<template>
  <div class="menu-wrapper" v-if="!item.hidden">
    <!-- 没有下拉菜单，子路由只有一个 -->
    <router-link :to="resolvePath(onlyOneChild.path)" v-if="hasOneShowingChild(item.children)" class="menu-item">
      <el-menu-item :index="resolvePath(onlyOneChild.path)">
        <template slot="title">
          <i v-if="onlyOneChild.meta.icon"><img src="./image/table.png" alt=""></i>
          <span slot="title">{{onlyOneChild.meta.title}}</span>
        </template>
      </el-menu-item>
    </router-link>
    <!-- 有下拉菜单，子路由不止一个 -->
    <el-submenu v-if="!hasOneShowingChild(item.children)" :index="item.path">
      <template slot="title">
        <i v-if="item.meta.icon"><img src="./image/table.png" alt=""></i>
        <span slot="title">{{item.meta.title}}</span>
      </template>
      <template v-for="child in item.children" v-if="!child.hidden">
        <siderBarItem v-if="child.children && child.children.length>0" :item="child" :key="child.path" :basePath="resolvePath(child.path)">
        </siderBarItem>
        <router-link class="menu-item" v-else :to="resolvePath(child.path)" :key="child.name">
          <el-menu-item :index="resolvePath(child.path)">
              <span v-if="child.meta&&child.meta.title" slot="title">{{child.meta.title}}</span>
          </el-menu-item>
        </router-link>
      </template>
    </el-submenu>
  </div>
</template>

<script>
import path from 'path'
export default {
  name: 'siderBarItem',
  props: [
    'item',
    'basePath',
    'isNest'
  ],
  data () {
    return {
      onlyOneChild: null
    }
  },
  methods: {
    hasOneShowingChild (children) {
      const showingChildren = children.filter(item => {
        if (item.hidden) {
          return false
        } else {
          this.onlyOneChild = item
          return true
        }
      })
      if (showingChildren.length === 1) {
        return true
      }
      return false
    },
    resolvePath (...paths) {
      return path.resolve(this.basePath, ...paths)
    }
  }

}
</script>

<style lang="less" scoped>
.menu-item{
  text-decoration: none;
}
i{
  margin:  5px;
}
</style>
